cmake_minimum_required(VERSION 3.12)
project(modbus_pressure_test VERSION 1.0.0 LANGUAGES C)

# 设置C标准
set(CMAKE_C_STANDARD 11)
set(CMAKE_C_STANDARD_REQUIRED ON)
set(CMAKE_C_EXTENSIONS OFF)

# 设置默认构建类型
if(NOT CMAKE_BUILD_TYPE)
    set(CMAKE_BUILD_TYPE Release)
endif()

# 查找依赖库
find_package(PkgConfig REQUIRED)
pkg_check_modules(LIBMODBUS REQUIRED libmodbus)

# 查找线程库
find_package(Threads REQUIRED)

# 检查实时系统支持
include(CheckSymbolExists)
check_symbol_exists(MLOCKALL "sys/mman.h" HAVE_MLOCKALL)
check_symbol_exists(SCHED_FIFO "sched.h" HAVE_SCHED_FIFO)

if(HAVE_MLOCKALL AND HAVE_SCHED_FIFO)
    message(STATUS "Real-time features enabled")
    add_definitions(-DHAVE_RT_FEATURES)
else()
    message(WARNING "Real-time features not fully supported")
endif()

# 添加可执行文件
add_executable(modbus_pressure_test
    src/main.c
    src/config.c
    src/modbus_client.c
    src/common.c
    src/pressure_test.c
    src/logger.c
)

# 包含目录
target_include_directories(modbus_pressure_test PRIVATE
    ${CMAKE_CURRENT_SOURCE_DIR}/include
    ${LIBMODBUS_INCLUDE_DIRS}
)

# 链接库
target_link_libraries(modbus_pressure_test PRIVATE
    ${LIBMODBUS_LIBRARIES}
    Threads::Threads
    m  # 数学库
    rt # 实时库
)

# 编译器选项
target_compile_options(modbus_pressure_test PRIVATE
    -Wall
    -Wextra
    -Wpedantic
    -Werror
    -D_GNU_SOURCE
    -D_POSIX_C_SOURCE=200112L
)

# 实时系统优化选项
target_compile_options(modbus_pressure_test PRIVATE
    -fno-strict-aliasing
    -fomit-frame-pointer
    -march=native
)

# Release模式优化
if(CMAKE_BUILD_TYPE STREQUAL "Release")
    target_compile_options(modbus_pressure_test PRIVATE
        -O2
        -ffast-math
        -funroll-loops
    )
    target_compile_definitions(modbus_pressure_test PRIVATE NDEBUG)
else()
    target_compile_options(modbus_pressure_test PRIVATE
        -O0
        -g3
        -DDEBUG
    )
endif()

# 安装目标
install(TARGETS modbus_pressure_test
    RUNTIME DESTINATION bin
)

# 安装配置文件
install(FILES settings.json DESTINATION share/modbus_pressure_test)
